<template>
	<view class="page-deliveryAdd">
		<view v-for="(address, addressIndex) in sortedAddresses" :key="addressIndex" class="addressInfo">
			<view class="address">
				{{address.address}}
			</view>
			<view class="addDetail">
				{{address.remarks}}
			</view>
			<view class="box">
				<view class="name">
					{{address.name}}&nbsp;
					{{address.phone}}
				</view>
				<view class="default">
					<text v-if="address.isDefault === true" class="">默认</text>
				</view>
			</view>
			<view class="action">
				<view class="imgContainer" @click="deleteAddress(address.addressID)">
					<view class="">
						删除
					</view>
					<image class="img" src="../../static/images/delete.png" mode=""></image>
				</view>
				<view class="imgContainer" @click="goTodeliveryUpdate(address.addressID)">
					<view class="">
						修改
					</view>
					<image class="img" src="../../static/images/alter.png" mode=""></image>
				</view>
			</view>

			<view class="line"></view>
		</view>
		<button class="button-yuanjiao" hover-class="bg-click" @click="goTodeliveryAdd()">新增收货地址</button>
	</view>
</template>

<script>
	import axios from 'axios';
	import service from '../../utils/request.js';
	import waterfall from '../../components/waterFall/waterFall.vue';
	export default {
		data() {
			return {
				userID: localStorage.getItem("userID"),
				addresses: []
			};
		},
		computed: {
		  sortedAddresses() {
		    // 返回排序后的地址数组，`default` 为 true 的地址会排在前面
		    return this.addresses.sort((a, b) => b.isDefault - a.isDefault);
		  }
		},
		methods: {
			async getAddressData() {
				try {
					const response = await service.get('/address/list/' + this.userID);
					this.addresses = response.data;
					console.log('获取的数据:', response);
				} catch (error) {
					console.error('获取数据失败:', error);
				}
			},
			async deleteAddress(addressID) {
				try {
					// 确认 goodsID 的类型是整数
					const response = await service.delete('/address/delete/' + addressID);
					console.log('获取的数据:', response);
				} catch (error) {
					console.error('获取数据失败:', error);
				}
			},
			goTodeliveryAdd() {
				uni.navigateTo({
					url: '/pages/deliveryAdd/deliveryAdd'
				});
			},
			goTodeliveryUpdate(addressID) {
				uni.setStorageSync('addressID', addressID)
				uni.navigateTo({
					url: '/pages/deliveryUpdate/deliveryUpdate?addressID=${addressID}'
				});
			},

		},
		onShow() {
			this.getAddressData();
		}
	}
</script>

<style lang="scss" scoped>
	@use "deliveryAddList";
</style>